import io from 'socket.io-client'

const eventMap = new Map();
export var socket;

export function connect(url) {
  if (socket == null || socket.disconnected) {
    socket = io.connect(url);

    socket.on("connect", function () {
      console.log("connect");
    });
    socket.on("disconnect", function () {
      console.log("disconnect");
    });
    socket.on("WebSocketPakcetEventName", function (packet) {
      if (!validatenull(packet) && packet.type === 3) {
        var eventName = packet.subType;
        var dataContent = packet.dataContent;
        if (!validatenull(dataContent)) {
          if (eventMap.has(eventName)) {
            var func = eventMap.get(eventName);
            func(socket, JSON.parse(dataContent));
          }
        }

      }
    });
  }


};

export function sendToSessionId(eventName, sessionId, data) {
  if (!validatenull(eventName) && socket != null && !validatenull(data)) {
    var p = {
      type: 3,
      subType: eventName,
      sessionId: sessionId,
      dataContent: JSON.stringify(data),
      ack: false,
      ackId: ""
    };
    socket.emit("WebSocketPakcetEventName", p);
  }
}

export function sendToServer(eventName, data) {
  sendToSessionId(eventName, "0", data);
}

export function sendToSessionIdReceive(toEventName, sessionId, data, recvEventName, timeout = 5000) {
  return new Promise(function (resolve, reject) {
    var removeListenerTimeout = undefined;

    eventMap.set(recvEventName, function (c, data) {
      if (removeListenerTimeout != undefined) {
        clearTimeout(removeListenerTimeout);
      }
      removeEventListener(recvEventName);
      resolve(data);
    });
    sendToSessionId(toEventName, sessionId, data);

    removeListenerTimeout = setTimeout(() => {
      removeEventListener(recvEventName);
      reject('timeout ' + timeout / 1000 + 's');
    }, timeout);
  });
}

export function sendToServerReceive(toEventName, data, recvEventName, timeout = 5000) {
  return sendToSessionIdReceive(toEventName, "0", data, recvEventName, timeout);
}

export function addEventListener(eventName, func) {
  removeEventListener(eventName);
  eventMap.set(eventName, func)
};

export function removeEventListener(eventName) {
  if (eventMap.has(eventName)) {
    eventMap.delete(eventName);
  }
};

export function validatenull(val) {
  if (val instanceof Array) {
    if (val.length == 0) return true;
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === '{}') return true;
  } else {
    if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
    return false;
  }
  return false;

};
